package com.godyao.controller;

import com.godyao.annotations.LimitAccessor;
import com.godyao.enums.ResponseCodeEnum;
import com.godyao.enums.ResultMsg;
import com.godyao.repository.GoodsRepository;
import com.godyao.repository.OrderRepository;
import com.godyao.service.SecKillService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;


/**
 * @author godyao
 * @date 2022/3/17
 */
@Slf4j
@CacheConfig(cacheNames = "secKill")
@RestController
@RequestMapping("/v1")
public class SecKillController {
    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private OrderRepository orderRepository;

    @Autowired
    private SecKillService secKillService;

    /**
     * 缓存前qps 95.5
     * 缓存后qps 2270
     * @return
     */
    @Cacheable
    @GetMapping("/goods")
    public ResultMsg goods() {
        return new ResultMsg(ResponseCodeEnum.OK, goodsRepository.findAll());
    }

    @GetMapping("/order")
    public ResultMsg orders() {
        return new ResultMsg(ResponseCodeEnum.OK, orderRepository.findAll());
    }

    @GetMapping("/secKillGoods")
    public ResultMsg secKillGoods() {
        return new ResultMsg(ResponseCodeEnum.OK, goodsRepository.findAll());
    }

    @GetMapping("/secKillOrders")
    public ResultMsg secKillOrders() {
        return new ResultMsg(ResponseCodeEnum.OK, orderRepository.findAll());
    }

    @LimitAccessor(count = 1, time = 1)
    @GetMapping("/secKill/{code}/{goodsId}")
    public ResultMsg secKill(@PathVariable Long goodsId, @PathVariable String code) {
        if (!secKillService.checkUrlInvalid(code, goodsId)) {
            log.info("url code验证不通过");
            return new ResultMsg(ResponseCodeEnum.FAIL, null);
        }
        return secKillService.secKill(goodsId);
    }

    @LimitAccessor(count = 1, time = 10)
    @GetMapping("/secKill/getOrderStatus")
    public ResultMsg getOrderStatus(Long goodsId) {
        return new ResultMsg(ResponseCodeEnum.OK, secKillService.getOrderStatus(goodsId));
    }

    @GetMapping("/secKill/generateSecKillCode/{goodsId}")
    public ResultMsg generateSecKillCode(@PathVariable Long goodsId) {
        String code = secKillService.generateSecKillCode(goodsId);
        return new ResultMsg(ResponseCodeEnum.OK, code);
    }
}
